package com.soriya.nestlive.screen.search

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.soriya.nestlive.component.ChannelItem
import com.soriya.nestlive.component.CustomEditText
import com.soriya.nestlive.component.NavMenu
import com.soriya.nestlive.component.NavMenuItem
import com.soriya.nestlive.component.ScreenColumnContent
import com.soriya.nestlive.component.SmallText
import com.soriya.nestlive.component.VideoCard
import com.soriya.nestlive.constant.UIValue
import com.soriya.nestlive.db.AppDataBase
import com.soriya.nestlive.viewmodel.ChannelModel
import com.soriya.nestlive.viewmodel.VideoModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
fun SearchScreen(
    toChannelDetail: (Long) -> Unit,
    toVideoDetail: (Long) -> Unit
) {
    ScreenColumnContent {

        var isSearch by remember {
            mutableStateOf(false)
        }

        var key by remember {
            mutableStateOf("")
        }

        val focusRequester = remember {
            FocusRequester()
        }

        val coroutineScope = rememberCoroutineScope()

        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            CustomEditText(
                value = key,
                onValueChange = {
                    key = it
                    if (key.isEmpty()) isSearch = false
                },
                placeholder = "请输入搜索内容",
                shape = RoundedCornerShape(UIValue.SMALL_RADIUS),
                modifier = Modifier
                    .weight(1F)
                    .height(40.dp)
                    .focusRequester(focusRequester)
            )
            TextButton(onClick = {
                if (key.isNotEmpty()) isSearch = true
            }) {
                SmallText(text = "搜索")
            }
        }

        if (isSearch) Result(key, toChannelDetail, toVideoDetail)
        else History()

        LaunchedEffect(Unit) {
            focusRequester.requestFocus()
        }

    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun Result(
    key: String,
    toChannelDetail: (Long) -> Unit,
    toVideoDetail: (Long) -> Unit
) {
    val pagerState = rememberPagerState(initialPage = 0)
    val coroutineScope = rememberCoroutineScope()

    NavMenu {
        NavMenuItem(title = "频道", select = pagerState.currentPage == 0, size = 3) {
            coroutineScope.launch {
                pagerState.animateScrollToPage(0)
            }
        }
        NavMenuItem(title = "视频", select = pagerState.currentPage == 1, size = 3) {
            coroutineScope.launch {
                pagerState.animateScrollToPage(1)
            }
        }
    }

    HorizontalPager(
        pageCount = 2,
        state = pagerState,
        pageSpacing = UIValue.HORIZONTAL_PADDING,
        modifier = Modifier.fillMaxSize()
    ) { page ->
        when (page) {
            0 -> ResultForChannel(key, toChannelDetail)
            1 -> ResultForVideo(key, toVideoDetail)
        }
    }
}


@Composable
private fun ResultForChannel(key: String, toChannelDetail: (Long) -> Unit) {
    val channelModel: ChannelModel = hiltViewModel()
    val searchResult = channelModel.search(key).collectAsLazyPagingItems()

    LazyColumn {
        items(
            count = searchResult.itemCount,
            key = searchResult.itemKey { it.id!! }
        ) {
            val data = searchResult[it]
            ChannelItem(data = data!!, isFollow = false, toChannelDetail = toChannelDetail)
        }
    }

}

@Composable
private fun ResultForVideo(key: String, toVideoDetail: (Long) -> Unit) {
    val videoModel: VideoModel = hiltViewModel()
    val searchResult = videoModel.search(key).collectAsLazyPagingItems()

    LazyColumn {
        items(
            count = searchResult.itemCount,
            key = searchResult.itemKey { it.id }
        ) {
            val data = searchResult[it]
            VideoCard(data = data!!) {
                toVideoDetail(data.id)
            }
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun History() = Column(
    modifier = Modifier.padding(top = UIValue.VERTICAL_PADDING)
) {
    Row(
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.fillMaxWidth()
    ) {
        SmallText(text = "搜索历史")

        IconButton(onClick = { /*TODO*/ }) {
            Icon(
                imageVector = Icons.Default.DeleteForever,
                contentDescription = "Remove All",
                modifier = Modifier.size(18.dp)
            )
        }
    }

    FlowRow(
        horizontalArrangement = Arrangement.spacedBy(10.dp)
    ) {
        SearchHistoryItem("搜索")
        SearchHistoryItem("搜索搜索")
        SearchHistoryItem("搜索")
        SearchHistoryItem("搜索搜索")
        SearchHistoryItem("搜索")
        SearchHistoryItem("搜索")
        SearchHistoryItem("搜索搜索")
    }
}


@Composable
private fun SearchHistoryItem(
    text: String
) = Text(
    text = text,
    textAlign = TextAlign.Center,
    fontSize = 14.sp,
    modifier = Modifier
        .padding(vertical = 5.dp)
        .clip(RoundedCornerShape(UIValue.SMALLER_RADIUS))
        .background(MaterialTheme.colors.surface.copy(0.2F))
        .padding(horizontal = 10.dp, vertical = 6.dp)
)